#ifndef AI_DETECTION_H
#define AI_DETECTION_H

// 历史采样窗口大小
#define HISTORY_WINDOW 20

class AIFaultDetector {
private:
  float baseline[4];          // 基线值
  float thresholds[4];        // 阈值
  float history[4][HISTORY_WINDOW]; // 历史数据
  int historyIndex;           // 当前历史数据索引
  int sampleCount;            // 样本计数
  float lastValues[4];        // 上一次传感器值
  unsigned long lastCheckTime; // 上一次检查时间
  
  // 计算标准差（用于增强故障检测）
  float calculateStdDev(float values[], int count) {
    float sum = 0.0, mean = 0.0;
    for (int i = 0; i < count; i++) {
      sum += values[i];
    }
    mean = sum / count;
    
    float squaredDiffSum = 0.0;
    for (int i = 0; i < count; i++) {
      squaredDiffSum += (values[i] - mean) * (values[i] - mean);
    }
    
    return sqrt(squaredDiffSum / count);
  }
  
  // 检测传感器卡死
  bool isSensorStuck(int channel, float currentValue) {
    const float STUCK_THRESHOLD = 0.001; // 非常小的变化被认为是卡死
    const int STUCK_COUNT_THRESHOLD = 10; // 连续相同值的次数阈值
    
    if (abs(currentValue - lastValues[channel]) < STUCK_THRESHOLD) {
      static int stuckCount[4] = {0};
      stuckCount[channel]++;
      if (stuckCount[channel] >= STUCK_COUNT_THRESHOLD) {
        stuckCount[channel] = 0;
        return true;
      }
    } else {
      stuckCount[channel] = 0;
    }
    
    lastValues[channel] = currentValue;
    return false;
  }
  
  // 检测传感器值波动异常
  bool isFluctuationAbnormal(int channel) {
    float stdDev = calculateStdDev(history[channel], HISTORY_WINDOW);
    // 标准差过大表示波动异常
    return stdDev > (baseline[channel] * 0.3); // 超过基线的30%
  }
  
  // 检测传感器值是否超出合理范围
  bool isOutOfRange(int channel, float value) {
    const float RANGE_THRESHOLD = 2.0; // 基线的2倍作为范围上限
    return (value < 0 || value > baseline[channel] * RANGE_THRESHOLD);
  }
  
  // 检测传感器响应时间异常
  bool isResponseTimeAbnormal() {
    const unsigned long MAX_RESPONSE_TIME = 1000; // 最大响应时间1秒
    unsigned long currentTime = millis();
    bool abnormal = (currentTime - lastCheckTime > MAX_RESPONSE_TIME);
    lastCheckTime = currentTime;
    return abnormal;
  }

public:
  AIFaultDetector() {
    // 初始化基线值和阈值
    for (int i = 0; i < 4; i++) {
      baseline[i] = 0.0;
      thresholds[i] = 0.2; // 20%变化阈值
      lastValues[i] = 0.0;
      for (int j = 0; j < HISTORY_WINDOW; j++) {
        history[i][j] = 0.0;
      }
    }
    sampleCount = 0;
    historyIndex = 0;
    lastCheckTime = 0;
  }
  
  // 设置基线值（外部调用）
  void setBaseline(float* newBaseline) {
    for (int i = 0; i < 4; i++) {
      baseline[i] = newBaseline[i];
      // 初始化历史数据
      for (int j = 0; j < HISTORY_WINDOW; j++) {
        history[i][j] = newBaseline[i];
      }
    }
    sampleCount = HISTORY_WINDOW;
    lastCheckTime = millis();
  }
  
  // 重置检测器
  void reset() {
    for (int i = 0; i < 4; i++) {
      baseline[i] = 0.0;
      thresholds[i] = 0.2;
      lastValues[i] = 0.0;
      for (int j = 0; j < HISTORY_WINDOW; j++) {
        history[i][j] = 0.0;
      }
    }
    sampleCount = 0;
    historyIndex = 0;
    lastCheckTime = millis();
  }
  
  // 设置阈值
  void setThresholds(float* newThresholds) {
    for (int i = 0; i < 4; i++) {
      thresholds[i] = newThresholds[i];
    }
  }
  
  // 校准算法
  void calibrate(float* values) {
    // 累积样本进行校准
    if (sampleCount < 100) {
      for (int i = 0; i < 4; i++) {
        baseline[i] = (baseline[i] * sampleCount + values[i]) / (sampleCount + 1);
      }
      sampleCount++;
    }
  }
  
  // AI增强的故障检测算法
  int detectFault(float* values) {
    // 更新历史数据
    for (int i = 0; i < 4; i++) {
      history[i][historyIndex] = values[i];
    }
    historyIndex = (historyIndex + 1) % HISTORY_WINDOW;
    
    // 如果样本数不足，先不进行故障检测
    if (sampleCount < HISTORY_WINDOW) {
      return -1;
    }
    
    // 检查系统响应时间
    if (isResponseTimeAbnormal()) {
      return 4; // 特殊代码表示系统响应异常
    }
    
    // 对每个传感器进行多维度故障检测
    for (int i = 0; i < 4; i++) {
      // 检查基本阈值差异
      if (abs(values[i] - baseline[i]) > thresholds[i]) {
        return i; // 返回故障通道索引
      }
      
      // 检查传感器是否卡死
      if (isSensorStuck(i, values[i])) {
        return i; // 传感器卡死
      }
      
      // 检查传感器是否超出合理范围
      if (isOutOfRange(i, values[i])) {
        return i; // 传感器值超出范围
      }
      
      // 检查传感器波动是否异常
      if (isFluctuationAbnormal(i)) {
        return i; // 传感器波动异常
      }
    }
    
    return -1; // 无故障
  }
  
  // 获取当前基线值
  void getBaseline(float* outBaseline) {
    for (int i = 0; i < 4; i++) {
      outBaseline[i] = baseline[i];
    }
  }
  
  // 获取当前阈值
  void getThresholds(float* outThresholds) {
    for (int i = 0; i < 4; i++) {
      outThresholds[i] = thresholds[i];
    }
  }
};

#endif